package com.kuaidian.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kuaidian.model.api.ResponseMsg;
import com.kuaidian.model.api.ResponseObj;
import com.kuaidian.pojo.Row;
import com.kuaidian.pojo.TUser;
import com.kuaidian.service.PhotoService;
import com.kuaidian.service.RedisService;
import com.kuaidian.service.UserService;
import com.kuaidian.util.AuthPassport;
import com.kuaidian.util.CommonUtil;
import com.kuaidian.util.JacksonMgr;
import com.kuaidian.util.MD5Util;
import com.kuaidian.util.constant.Constant;
import com.kuaidian.util.constant.ErrorCode;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;


@Api(value="Common",description="client")
@Controller
@RequestMapping( "/api/client" )
public class ClientController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;
    @Autowired
    PhotoService photoService;
    
    private static Logger logger = Logger.getLogger(ClientController.class);  
    
    @InitBinder     /* Converts empty strings into null when a form is submitted */
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
    
    
    @ApiOperation(value ="验证手机号是否已存在",notes="验证手机号是否已存在")
    @RequestMapping(value="users/check_tel",produces="application/json;charset=utf-8",method = RequestMethod.GET)
    public @ResponseBody Object register(@RequestParam String tel){
    	try {
    		TUser user = new TUser();
    		user.setTel(tel);
    		user.setDel(Constant.DEL_NO);
        	int count = userService.selectCount(user);
        	ResponseMsg retMsg = null;
        	if (count > 0) {
        		retMsg = new ResponseMsg("该手机号已使用",ErrorCode.ERROR, null);
			}else{
				retMsg = new ResponseMsg("",ErrorCode.OK, null);
			}
        	String jsonString = JacksonMgr.toJSON(retMsg);
    		return jsonString;
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return JacksonMgr.makeExceptionJSON(e);
		}
    }
    
	@ApiOperation(value ="注册",notes="注册")
    @RequestMapping(value="users/register",produces="application/json;charset=utf-8",method = RequestMethod.GET)
    public @ResponseBody Object register(@RequestParam String tel,
    									 @RequestParam String pwd,
    									 @RequestParam String nickname){
    	try {
    		TUser user = new TUser();
    		user.setTel(tel);
    		user.setNickname(nickname);
    		user.setPwd(MD5Util.encodeByMD5(pwd));
    		user.setIcon(Constant.DEFAULT_ICON);
    		user.setCreate_time(new Date());
        	ResponseMsg retMsg = null;
        	int count = userService.insertUser(user);
        	if (count != 1) {
        		retMsg = new ResponseMsg("注册失败",ErrorCode.ERROR,null);
			}else{
				retMsg = new ResponseMsg("注册成功",ErrorCode.OK, null);
			}
        	String jsonString = JacksonMgr.toJSON(retMsg);
    		return jsonString;
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return JacksonMgr.makeExceptionJSON(e);
		}
    }

	
	@ApiOperation(value ="登录",notes="登录")
    @RequestMapping(value="users/login",produces="application/json;charset=utf-8",method = RequestMethod.GET)
    public @ResponseBody Object register(@RequestParam String tel,
    									 @RequestParam String pwd){
    	try {
    		TUser user_p = new TUser();
    		user_p.setTel(tel);
    		user_p.setPwd(MD5Util.encodeByMD5(pwd));
    		user_p.setDel(Constant.DEL_NO);
        	ResponseMsg retMsg = null;
        	List<TUser> user_list = userService.select(user_p);
        	if (user_list.size() < 1) {
        		retMsg = new ResponseMsg("登录失败",ErrorCode.ERROR,null);
			}else{
				TUser user_r = user_list.get(0);
				Integer user_id = user_r.getId();
				String token = MD5Util.encodeByMD5(String.valueOf(System.currentTimeMillis()).substring(7,13) + user_id);
				redisService.cacheLoginedUser(user_id, token);
				Row row = new Row();
				row.put("user_nickname", user_r.getNickname());
				row.put("user_icon", user_r.getIcon());
				ResponseObj responseObj = new ResponseObj(user_id + "", token, row); 
				retMsg = new ResponseMsg("登录成功",ErrorCode.OK,responseObj);
			}
        	String jsonString = JacksonMgr.toJSON(retMsg);
    		return jsonString;
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return JacksonMgr.makeExceptionJSON(e);
		}
    }
	

	 @ApiOperation(value ="首页",notes="首页")
	 @RequestMapping(value="homepage",produces="application/json;charset=utf-8",method = RequestMethod.GET)
	 public @ResponseBody Object homepage(@RequestParam(required=false) Integer user_id,
			 							  @RequestParam Integer pageSize, 
			   							  @RequestParam Integer curPage){
	    	try {
	    		Integer startRow = CommonUtil.curPage2Start(pageSize, curPage);
	    		List<Row> result_list = photoService.selectHomepage(user_id, startRow, pageSize);
	        	ResponseMsg retMsg = null;
	        	retMsg = new ResponseMsg("成功",ErrorCode.OK, result_list);
	        	String jsonString = JacksonMgr.toJSON(retMsg);
	    		return jsonString;
			} catch (Exception e) {
				logger.error(e);
				return JacksonMgr.makeExceptionJSON(e);
			}

	    }
	 
	 
	 
	   //MIS 创建 session
		@ApiOperation(value = "MIS登录，创建会话")
		@AuthPassport(validate=false)
		@RequestMapping(value="MISUser/sessions",produces="application/json;charset=utf-8",method = RequestMethod.POST)
		public @ResponseBody Object postSession(@RequestParam String userName,@RequestBody String pwd,HttpServletRequest request) { 
		try {
			ResponseMsg retMsg = null;
			if (Constant.SUPER_ADMIN.equals(userName) && Constant.SUPER_ADMIN_PWD.equals(pwd)) {
				// 创建 session
				HttpSession session = request.getSession(true);
				session.setAttribute("userName", userName);
				retMsg = new ResponseMsg("成功", ErrorCode.OK, null);
			} else {
				retMsg = new ResponseMsg("用户名密码错误", ErrorCode.ERROR, null);
			}
			String jsonString = JacksonMgr.toJSON(retMsg);
			return jsonString;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return JacksonMgr.makeExceptionJSON(e);
		}
		}
	
	 @ApiOperation(value ="测试链接",notes="测试链接")
	    @RequestMapping(value="users/test",produces="application/json;charset=utf-8",method = RequestMethod.GET)
	    public @ResponseBody Object test(){
	    	try {
	        	ResponseMsg retMsg = null;
	        	retMsg = new ResponseMsg("成功",ErrorCode.OK, null);
	        	String jsonString = JacksonMgr.toJSON(retMsg);
	    		return jsonString;
			} catch (Exception e) {
				logger.error(e);
				return JacksonMgr.makeExceptionJSON(e);
			}

	    }

	 

 	 
}
